<template>
  <a-modal v-model="downloadShowFun"
           title="下载数据"
           ok-text="确定"
           cancel-text="取消"
           @ok="submitForm('ruleForm')"
           @cancel="resetForm('ruleForm')"
           class="downloadFrame"
           width="440">

    <a-form-model ref="ruleForm"
                  :model="ruleForm"
                  :rules="rules"
                  v-bind="layout"
                  class="formFrame">

      <a-form-model-item label="监测点名称"
                         class="formItemText">
        <p>{{downData.name}}</p>
      </a-form-model-item>

      <a-form-model-item label="设备名称"
                         class="formItemText">
        <p>{{downData.dname}}</p>
      </a-form-model-item>

      <a-form-model-item label="数据频率"
                         prop="dateChoose">
        <a-select v-model="ruleForm.dateChoose"
                  placeholder="时均值">
          <a-select-option value="时均值">
            时均值
          </a-select-option>
          <a-select-option value="日均值">
            日均值
          </a-select-option>
        </a-select>
      </a-form-model-item>

      <!-- 时间区间-时区间 -->
      <a-form-model-item label="时间区间"
                         prop="dateGroup"
                         class="chooseDate">
        <!-- 日期 年-月-日 -->
        <a-range-picker @change="onChangeDate"
                        :default-value="[moment(ruleForm.startDate, dateFormat), moment(ruleForm.endDate, dateFormat)]"
                        :model="ruleForm.dateGroup"
                        :disabled-date="disabledDate"
                        :getCalendarContainer="(triggerNode) => triggerNode.parentNode">
          <a-icon slot="suffixIcon"
                  type="calendar" />
        </a-range-picker>
        <!-- <a-input v-model.number="ruleForm.age" /> -->
      </a-form-model-item>

      <!-- 检测失败图标 -->
      <!-- <a-form-model-item label="下载到"
                         prop="address"> -->
      <!-- </a-form-model-item> -->
      <!-- <a-form-model-item label="下载到"
                         prop="address">
        <a-input v-model="ruleForm.address" />
      </a-form-model-item> -->

    </a-form-model>

  </a-modal>

</template>
<script>
import moment from 'moment'
import Com from '../../../common/js/com.js'
import MixinSD from '../../../store/sd/mixinsSd.js'
import ExportExcel from '../../../export/index.js'
export default {
  mixins: [MixinSD],
  props: ['downloadShow', 'downData'], /* downloadShow: 下载框显示状态   downData: 当前选择的数据列 */
  data () {
    // const validatePass = (rule, value, callback) => {
    //   if (rule.field === 'address') {
    //     if (value === '') {
    //       callback(new Error('请输入下载地址'))
    //     } else {
    //       callback()
    //     }
    //   } else if (rule.field === 'dateGroup') {
    //     if (value === '' || value.indexOf(null) !== -1 || value.length === 0) {
    //       callback(new Error('请选择日期'))
    //     } else {
    //       const date1 = value[0]._d
    //       const date2 = value[1]._d
    //       const startDate1 = Date.parse(date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate())
    //       const endDate1 = Date.parse(date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate())
    //       const days = (endDate1 - startDate1) / (1 * 24 * 60 * 60 * 1000)
    //       if (days > 30) {
    //         callback(new Error('时间区间不可超过一个月，请重新选择！！'))
    //       } else {
    //         callback()
    //       }
    //     }
    //   }
    // }
    return {
      //   id: 'inputFile',
      dateFormat: 'YYYY-MM-DD',
      download: '1',
      ruleForm: {
        dateChoose: '', // 数据频率选择
        dateChooseId: '',
        address: '', // 下载地址
        startDate: null, // 日均值
        endDate: null, // 日均值
        dateGroup: [null, null] // 日期区间
      },
      rules: {
        // address: [{ validator: validatePass, trigger: 'change' }], // 下载地址
        // dateGroup: [{ validator: validatePass, trigger: 'change' }] // 选择日期
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      }
    }
  },
  created () {
    this.timeList = Com.timeList
    this.ruleForm.dateChoose = Com.timeDefaultName
    this.ruleForm.dateChooseId = Com.timeDefault
    var start = Com.getBeforeDate(7, 'date')
    var end = Com.getBeforeDate(0, 'date')
    this.ruleForm.startDate = start
    this.ruleForm.endDate = end
  },
  methods: {
    moment,
    disabledDate: function (current) { // 日期禁止
      return current && current > moment().endOf('day') // 不能今天之后的日期
    },
    chooseDateIdFun: function (val) {
      if (val === '时均值') {
        return 'H'
      } else {
        return 'D'
      }
    },
    onChangeDate: function (date, dateString) { // 日均值日期选择
      //   const startDate1 = Date.parse(dateString[0])
      //   const endDate1 = Date.parse(dateString[1])
      //   const days = (endDate1 - startDate1) / (1 * 24 * 60 * 60 * 1000)
      //   if (days > 30) {
      // this.$warning({
      //   title: '错误提示',
      //   content: '时间区间不可超过一个月，请重新选择！！'
      // })
      //   } else {
      const num = Com.dateDiff(dateString[0], dateString[1])
      if (num > 366) {
        this.$message.warning('最多只可以选择一年！')
      } else {
        this.ruleForm.startDate = dateString[0]
        this.ruleForm.endDate = dateString[1]
      }
      //   }
    },
    resetForm: function (formName) { /* 关闭-下载弹框 */
      this.$refs[formName].resetFields()
      this.$emit('hideDownModal', false)
    },
    submitForm: function (formName) { /* 确定-下载弹框 */
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.getDeviceLogList()
          //   this.$refs[formName].resetFields()
          //   this.$emit('hideDownModal', false)
        } else {
          return false
        }
      })
    },
    getDeviceLogList: function () {
      // 修改时间格式
      const idx = this.ruleForm.startDate.indexOf(' ')
      var minTime, maxTime
      const dateChooseId = this.chooseDateIdFun(this.ruleForm.dateChoose)
      if (idx !== -1) { // 年月日时分秒
        if (dateChooseId === 'D') {
          minTime = (this.ruleForm.startDate).substring(0, idx)
          maxTime = (this.ruleForm.endDate).substring(0, idx)
        }
      } else { // 年月日
        if (dateChooseId === 'H') {
          const time = Com.stringTime((new Date()), 'time')
          minTime = (this.ruleForm.startDate) + time
          maxTime = (this.ruleForm.endDate) + time
        }
      }

      var ts = Com.stringTime(new Date())
      var data = {
        account: window.localStorage.getItem('account'),
        codes: this.downData.code,
        datetype: dateChooseId,
        download: this.download,
        max_time: maxTime,
        min_time: minTime,
        token: window.localStorage.getItem('token'),
        ts
      }

      const that = this
      this.getDeviceLogListSD(data).then(function (value) {
        const result = value.data.data
        if (result.params && result.list) {
          that.getData(result, that)
        } else {
          that.$message.success('下载失败，稍后再试！')
        }
      })
    },
    getData: function (result, that) {
      const liTable = that.downData
      console.log(result)
      const columns = result.params.map(item => ({ key: item.name, title: item.name }))
      columns.unshift({ key: 'typename', title: '设备类型名称' })
      columns.unshift({ key: 'dname', title: '设备名称' })
      columns.push({ key: 'time', title: '更新时间' })

      const dataSource = result.list.map(item => {
        Object.keys(item).forEach(key => { // 后端传null node写入会有问题
          if (item[key] === null) {
            item[key] = ''
          }
          if (Array.isArray(item[key])) {
            item[key] = item[key].join(',')
          }
          item.typename = (liTable.typename)
          item.dname = (liTable.dname)
        })
        return item
      })
      const start = (this.ruleForm.startDate).replace(/-/g, '')
      const end = (this.ruleForm.endDate).replace(/-/g, '')
      ExportExcel(columns, dataSource, `${start}-${end}_${liTable.name}_导出.xlsx`)
      // ExportExcel(columns, dataSource, `${new Date().getTime().toString()}_${liTable.code}_导出.xlsx`)
    }
  },
  computed: {
    downloadShowFun: {
      get: function () {
        return this.downloadShow
      },
      set: function () {
        return !this.downloadShow
      }
    }
  }
}
</script>

<style lang="less" scoped>
.timeGroup {
  display: flex;
  align-items: center;
}
.timeGroup > span {
  font-size: 0.14rem;
  color: rgba(0, 0, 0, 0.65);
  width: 0.3rem;
  text-align: center;
}
</style>
